package com.wc.算法基础课.E第五讲动态规划.线性DP.编辑距离;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

/**
 * @Author congge
 * @Date 2024/5/11 9:47
 * @description https://www.acwing.com/problem/content/901/
 */
public class Main {
    static FastReader sc = new FastReader();
    static PrintWriter out = new PrintWriter(System.out);
    static int N = 1010, M = 15;
    static char[] s, t;
    static char[][] a = new char[N][];
    // f[i][j] 表示s匹配了i个,t匹配了j个的最小匹配次数
    static int[][] f = new int[M][M];
    static int n, m, p;

    public static void main(String[] args) {
        n = sc.nextInt();
        m = sc.nextInt();
        for (int i = 1; i <= n; i++) a[i] = (" " + sc.next()).toCharArray();
        while (m-- > 0) {
            s = (" " + sc.next()).toCharArray();
            p = sc.nextInt();
            int res = 0;
            for (int i = 1; i <= n; i++) {
                if (work(s, a[i])) res++;
            }
            out.println(res);
        }
        out.flush();
    }

    static boolean work(char[] s, char[] t) {
        int n = s.length - 1, m = t.length - 1;
        for (int i = 0; i <= n; i++) f[i][0] = i;
        for (int i = 0; i <= m; i++) f[0][i] = i;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                // 删除/插入
                f[i][j] = Math.min(f[i - 1][j] + 1, f[i][j - 1] + 1);
                // 替换
                if (s[i] == t[j]) f[i][j] = Math.min(f[i][j], f[i - 1][j - 1]);
                else f[i][j] = Math.min(f[i][j], f[i - 1][j - 1] + 1);
            }
        }

        return f[n][m] <= p;
    }
}

class FastReader {
    StringTokenizer st;
    BufferedReader br;

    FastReader() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String next() {
        while (st == null || !st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    String nextLine() {
        String s = "";
        try {
            s = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }

    // 是否由下一个
    boolean hasNext() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                String line = br.readLine();
                if (line == null)
                    return false;
                st = new StringTokenizer(line);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return true;
    }
}
